package cn.minimelon.solon.service.excel.impl;

import cn.hutool.core.util.StrUtil;
import cn.minimelon.solon.domain.excel.DeptGoodsDTO;
import cn.minimelon.solon.mapper.excel.YbGoodsMapper;
import cn.minimelon.solon.service.excel.DeptGoodsService;
import org.beetl.sql.solon.annotation.Db;
import org.noear.solon.annotation.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Component
public class DeptGoodsServiceImpl implements DeptGoodsService {

    private static final String UPDATE_SQL = "update dept_goods_info set packet_code=%s,pkg_def_id='%s' where id='%s';";

    @Db("writer")
    private YbGoodsMapper ybGoodsMapper;

    @Override
    public void writeFile(String fileName) throws Exception {
        List<DeptGoodsDTO> list = ybGoodsMapper.selectDeptGoodsList();

        List<String> ids = this.readFile("/home/Hiro/ZXTemp/科室产品设置小包脚本1666984146157.sql");
        FileOutputStream fos = new FileOutputStream(fileName);
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
        for (DeptGoodsDTO deptGoods : list) {
            if (ids.contains(deptGoods.getId())) {
                String sql = String.format(UPDATE_SQL, deptGoods.getSmallQty(), deptGoods.getSmallId(), deptGoods.getId());
                System.out.println(sql);
                bw.write(sql);
                bw.newLine();
            }
        }
        bw.close();
        fos.close();
    }

    @Override
    public List<String> readFile(String fileName) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(fileName));

        List<String> list = new ArrayList<>();
        String lastId = "";
        String line;
        while ((line = br.readLine()) != null) {
            int idx = line.indexOf("dept-goods-info-");
            String currId = line.substring(idx, line.length() - 2);
            if (StrUtil.isNotEmpty(lastId) && currId.equals(lastId)) {
                list.add(currId);
            } else {
                lastId = currId;
            }
        }

        list.stream().distinct().forEach(System.err::println);

        br.close();

        return list;
    }
}
